package com.pan.download5.factory.impl;

import com.pan.crawler.Directory;
import com.pan.download5.factory.DirectoryFactory;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class CommonDirectoryFactory implements DirectoryFactory {

    private Class directoryClass;

    public CommonDirectoryFactory(Class<? extends Directory> directoryClass) {
        if (Directory.class.isAssignableFrom(directoryClass)){
            this.directoryClass = directoryClass;
        }else {
            throw new RuntimeException("Error Directory Class: This is not Directory Class");
        }
    }

    @Override
    public Directory createDirectory() {
        try {
            Constructor constructor = directoryClass.getConstructor();
            Directory directory = (Directory) constructor.newInstance();
            return directory;
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

}
